package com.toune.villager.activity

import android.os.Bundle
import com.bumptech.glide.Glide
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxImageTool
import com.tamsiree.rxkit.RxSPTool
import com.toune.dltools.http.IBaseCallBack
import com.toune.dltools.ui.DLBaseActivity
import com.toune.villager.AppContant
import com.toune.villager.R
import com.toune.villager.bean.VerifyCodeImgBean
import com.toune.villager.model.LoginModel
import com.toune.villager.util.Base64ImageUtil
import kotlinx.android.synthetic.main.activity_login.*
import java.util.*

class LoginActivity : DLBaseActivity<LoginModel>() {
    override val layout: Int
        get() = R.layout.activity_login
    override val titleStr: String?
        get() = ""

    var verifyCodeImgBean: VerifyCodeImgBean? = null
    var codeExTime = 0;
    var timer: Timer? = null
    override fun init(savedInstanceState: Bundle?) {
        val tokenStr = RxSPTool.getString(context, AppContant.SP_TOKEN)
        if (tokenStr.isNotBlank()) {
            IBaseCallBack.headerMap["Authorization"] = "Bearer $tokenStr"
            RxActivityTool.skipActivityAndFinish(context, MainActivity::class.java)
            return
        }
        mViewModel.getCaptchaImage()
        mViewModel.verifyCodeImg.observe(this, {
            codeExTime = 0
            verifyCodeImgBean = it
            Glide.with(this).load(Base64ImageUtil.stringtoBitmap(verifyCodeImgBean!!.img))
                .into(verifyIv)
        })
        mViewModel.loginError.observe(this, {
            mViewModel.getCaptchaImage()
            et_verify.setText("")
        })
        if (timer == null) {
            timer = Timer()
            var timerTask = object : TimerTask() {
                override fun run() {
                    if (codeExTime >= 28) {
                        mViewModel.getCaptchaImage()
                        codeExTime = 0
                    } else {
                        codeExTime++
                    }
                }
            }
            timer!!.schedule(timerTask, 100, 1000)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (timer != null) {
            timer!!.cancel()
        }
        timer = null
    }

    override fun initEventAndData() {
        tv_login.setOnClickListener {
            mViewModel.login(
                context,
                et_account.text.toString(),
                et_psw.text.toString(),
                et_verify.text.toString(),
                verifyCodeImgBean!!.uuid
            )
        }
        verifyIv.setOnClickListener {
            mViewModel.getCaptchaImage()
            et_verify.setText("")
        }
    }


}